package RabbitMQ.WorkQueue;

import RabbitMQ.Constants.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo2 {
    public static void main(String[] args) throws IOException, TimeoutException {
//        建立连接
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        connectionFactory.setPort(Constants.PORT);
        Connection connection=connectionFactory.newConnection();
//        创建信道
        Channel channel=connection.createChannel();
//        使用内置的交换机
//       声明队列,如果队列不存在则创建,如果队列存在就不创建
        channel.queueDeclare(Constants.WORK_QUEUE,true,false,false,null);
//        消费消息
        DefaultConsumer consumer=new DefaultConsumer(channel){
            //            从队列中获取到消息就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到的消息: "+new String(body));
            }
        };
        channel.basicConsume(Constants.WORK_QUEUE,true,consumer);

    }

}
